package com.lw.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author LW
 * @2020/8/20 16:07
 */
/**同步队列
 * 和其他的BlockingQueue不一样，   SynchronousQueue不存储元素
 * put了一个元素，必须从里面先take出来，否则就不能put
 * 任意时间只能有一个线程操作
 */

public class SynchronousQueueDemo {
    /**
     * SynchronousQueue       同步锁
     * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
     * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
     * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
     * 错的！！！！！！！！！！！！！！！！！！！！！！！
     * @param args
     */
    public static void main(String[] args) {
        //<>泛型：           约束元素的类型
        BlockingQueue<String> synchronousQueue = new SynchronousQueue<>();//同步队列
        ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
        new Thread(()->{
            try {
                rwLock.writeLock().lock();
                synchronousQueue.put("1");
                System.out.println(Thread.currentThread().getName()+"==>put 1");
                synchronousQueue.put("2");
                System.out.println(Thread.currentThread().getName()+"==>put 2");
                synchronousQueue.put("3");
                System.out.println(Thread.currentThread().getName()+"==>put 3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                rwLock.writeLock().unlock();
            }
        },"A").start();
        new Thread(()->{
            try {
                rwLock.readLock().lock();
                System.out.println(Thread.currentThread().getName()+"-->"+synchronousQueue.take());
                System.out.println(Thread.currentThread().getName()+"-->"+synchronousQueue.take());
                System.out.println(Thread.currentThread().getName()+"-->"+synchronousQueue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                rwLock.readLock().unlock();
            }
        },"B").start();
    }
}
